package com.google.code.p.androidbuildinfo;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Base64;
import android.view.Menu;
import android.webkit.WebView;

public class ConstantListActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_constant_list);
        
        StringBuilder html = new StringBuilder("<html><head><meta charset=\"UTF-8\"/>")
        	.append("<style type=\"text/css\">th { text-align: left; text-transform: none; } td, th { white-space: nowrap; }</style>")
        	.append("</head><body><table>");
        Class<Build> build = Build.class;
        for(Class<?> innerClass: build.getDeclaredClasses())
        {
        	appendFields(innerClass.getSimpleName()+".", html, innerClass);
        }
        appendFields("", html, build);
        html.append("</table></body></html>");
        
        WebView infoDisplay = (WebView) findViewById(R.id.infoDisplay);
        
        try {
			infoDisplay.loadData(Base64.encodeToString(html.toString().getBytes("UTF-8"), Base64.DEFAULT),
					"text/html",
					"base64");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
    }

	private void appendFields(String prefix, StringBuilder html, Class<?> build) {
		for(Field f: build.getFields())
        {
        	if(Modifier.isStatic(f.getModifiers()))
        	{
        		Object value = "<em>error</em>";
				try {
					value = f.get(null);
					value = TextUtils.htmlEncode(String.valueOf(value));
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				}
				html.append("<tr><th>")
        			.append(TextUtils.htmlEncode(prefix+f.getName()))
        			.append("</th><td>")
        			.append(TextUtils.htmlEncode(f.getType().getSimpleName()))
        			.append("</td><td>")
        			.append(value.toString())
        			.append("</td></tr>");
        	}
        }
	}

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_constant_list, menu);
        return true;
    }
    
}
